package com.zyw.teacher.login.service.impl;

import com.zyw.teacher.login.entity.Role;
import com.zyw.teacher.login.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description: 根据请求返回请求资源对应的角色列表
 * @Author: zyw
 * @Date: 2018/12/14
 */
@Component
public class DataBaseFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IRoleService roleService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation fi = (FilterInvocation) object;
        String url = fi.getRequestUrl();
        String httpMethod = fi.getRequest().getMethod();
        List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>();
        // Lookup your database (or other source) using this information and populate the
        // list of attributes
        List<Role> roles = roleService.queryByUrl(url);
        roles.forEach(obj->{
            attributes.add(obj);
        });
        return attributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        Set<ConfigAttribute> allAttributes = new HashSet<>();
        List<Role> roles = roleService.getAllRole();
        if(roles != null || roles.size() > 0){
            roles.forEach(obj->{
                allAttributes.add(obj);
            });
        }
        return allAttributes;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return ConfigAttribute.class.isAssignableFrom(clazz);
    }
}
